package com.laycoding.consumer.proxy;

import com.laycoding.common.entity.RpcMessage;
import com.laycoding.common.util.LoadBlance;
import com.laycoding.common.util.ZkUtils;
import com.laycoding.consumer.handler.RpcProxyHandler;
import com.laycoding.consumer.service.RpcService;
import com.laycoding.consumer.service.RpcServiceImpl;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import org.apache.curator.framework.CuratorFramework;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

public class ServiceProxy implements InvocationHandler {
    private Class<?> clazz;

    public ServiceProxy(Class<?> clazz) {
        this.clazz = clazz;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 如果传进来是一个已实现的具体类
        if (Object.class.equals(method.getDeclaringClass())) {
            try {
                return method.invoke(this, args);
            } catch (Throwable t) {
                t.printStackTrace();
            }
            // 如果传进来的是一个接口（核心)
        } else {
            return rpcInvoke(method, args);
        }
        return null;
    }
    // 实现接口的核心方法
    public Object rpcInvoke(Method method, Object[] args) {
        // 传输协议封装
        RpcMessage invokerMessage = new RpcMessage();
        invokerMessage.setClassName(this.clazz.getName());
        invokerMessage.setMethodName(method.getName());
        invokerMessage.setValues(args);
        invokerMessage.setParams(method.getParameterTypes());
        RpcService rpcService = new RpcServiceImpl();
        return rpcService.sendMessage("192.168.1.125",8080,invokerMessage);
    }


}
